<?php

namespace App\Http\Controllers\VideoApi;

use App\Http\Config\ErrorCode;
use App\Http\Controllers\Controller;
use App\Models\video\UserTokenModel;
use Illuminate\Http\Request;

class BaseController extends Controller
{
    public $returnData;
    public $noCheckTokenAction = []; //不校验token的方法名

    public function __construct(Request $request)
    {
        /*--- start 跨域测试用 (待删除) ---*/
        header('Access-Control-Allow-Origin: *');                                                                 // 允许任意域名发起的跨域请求
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        /*--- end 跨域测试用---*/

        if($request->getMethod() == "OPTIONS"){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            return $this->returnData;
        }
        //处理登录token等信息
        if(!in_array(\request()->route()->getActionMethod(), $this->noCheckTokenAction)){
            if($request->token) { //就校验token是否有效或者过期
                if (!$userLoginData = $this->getTokenVar($request->token)) {
                    return false;
                }
                $request->userLoginData = $userLoginData; // 把信息存到request对象里，全局可以调用
            }else{
                $this->returnData = ErrorCode::code('token_not_exist');
                $this->returnData["msg"] = "请先登录";
                return false;
            }
        }
        $this->returnData = ErrorCode::$admin_enum['success'];
        return true;
    }

    public function getTokenVar($token, $key = ''){
        $data = UserTokenModel::checkToken($token);
        if(isset($data["code"])){
            $this->returnData = $data;
            return false;
        }
        if(empty($key)){
            return $data;
        }
        if (array_key_exists($key, $data)) {
            return $data[$key];
        }else{
            return "";
        }
    }

    //统一返回数据
    public function return_result(array $data, $text = '')
    {
        if(!is_array($data['msg']) && $text && strpos($data['msg'], "%s") !== false){
            $data['msg'] = sprintf($data['msg'], $text);
        }
        return response()->json($data);
    }
}
